var http = require('http');
var fs = require('fs');//引入文件读取模块
var url = require("url");

var documentRoot = 'D:/服务器开发/NodeJs/public';
//需要访问的文件的存放目录
var JsonPath = '';
//path模块，可以生产相对和绝对路径
var path = require("path");
var server= http.createServer(function(req,res)
{
    var filePath = path.resolve() + "/public"; 
    
    //客户端输入的url，例如如果输入localhost:8888/index.html
    //那么这里的url == /index.html 

    //客户端输入的url，例如如果输入localhost:8888/index.html
    //那么这里的url == /index.html 
	// var arg = url.parse(req.url).query;  //方法一arg => aa=001&bb=002
	// var p = url.parse(req.url);
	// var pst = p.host
	//console.log(url);
	
	
		// 获取请求路径
        var pathname = url.parse(req.url).pathname;
			      // 关闭nodejs 默认访问 favicon.ico
        if (!pathname.indexOf('/favicon.ico')) {
            return; 
        };
		
    var file = filePath + pathname;
	// console.log(file);
	// fs.readFile( file, function (err, data) {        
         // if( err ){
			// JsonPath = '';
			// walkJson(filePath);
			// JsonPath = JsonPath.substr(0,JsonPath.length-1);
			// JsonPath = "[" +  JsonPath  + "]" ;
			// console.log("123" + JsonPath);
			// jsonstr = JsonPath;
			// console.log(err);
         // }else{
			//// data.readFile(file);
          //     // response = {
            //       // message:'File uploaded successfully', 
            //      // filename:req.files[0].originalname
            //  // };
			   // res.writeHead(200, {
                        // 'Content-Type': "text/plain"
                    // });
			    // console.log( data );
				// res.end( JSON.stringify( data ) );  
          // }
    
   // });
	fs.readFile( file, function (err, data) {        
			 if( err ){
				JsonPath = '';
				walkJson(filePath);
				JsonPath = JsonPath.substr(0,JsonPath.length-1);
				JsonPath = "[" +  JsonPath  + "]" ;
				console.log("123" + JsonPath);
				jsonstr = JsonPath;
				res.end(jsonstr);
			 }else{
				   response = {
					   message:'File uploaded successfully', 
					   //filename:req.files[0].originalname
				  };
					console.log( response );
					res.end( JSON.stringify( response ) );  
			  }
		
	   });	   

 }).listen(8888);

console.log('服务器开启成功');
function walkJson(path){
	var dirList = fs.readdirSync(path);
	dirList.forEach(function(item){
		if(fs.statSync(path + '/' + item).isDirectory()){
			//walkJson(path + '/' + item);
			var ReFile = getRedir(path + '/' + item );
			JsonPath = JsonPath + "\"" + ReFile + "/\",";			
		}else{
			var ReFile = getRedir(path + '/' + item);
			JsonPath = JsonPath + "\"" + ReFile + "\",";			
		}			
	});
}
function getRedir(url){
 //console.log(url);
  var filePath = path.resolve() + "/upload/";
  var arr = url.split(filePath);
  var len = arr.length;
  //console.log(arr[len-1]);
  return arr[len-1];
}